<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'m8:machine:caozuo'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="85%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #m8OrderFlowWxOutRdsList>
        <BasicTable
          @register="registerM8OrderFlowWxOutRdsTable"
          @row-click="handleM8OrderFlowWxOutRdsRowClick"
          ref="tableRef"
        >
          <template #firstColumn="{ record }">
            <div v-if="record.erroMsg" class="text-red-700">{{  record.erroMsg  }}</div>
            <span v-else class="cursor-pointer">  {{ record.orderPic.picname }}  </span>
          </template>
        </BasicTable>
      </template>
    </BasicForm>

    <!-- <template #appendFooter>
      <a-button :loading="loading" v-if="record.outStatus != '4'" @click="handleSp()">
        <Icon icon="simple-line-icons:docs" /> {{ t('保存并审核') }}
      </a-button>
    </template> -->

    <!-- <Modal @register="register" @modifyjfdate="modifyjfdate" /> -->
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsOrderFlowWxM8OrderFlowXxForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed, nextTick } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    M8OrderFlowWxOut,
    m8OrderFlowWxOutSave,
    m8OrderFlowWxOutForm,
  } from '/@/api/m8/order/m8OrderFlowWxOut';
  import { repCheck } from '/@/api/m8/more/more'
  import { officeTreeData } from '/@/api/sys/office';
  import { ListSelect } from '/@/components/ListSelect';
  import Modal from './Modal.vue';
  import { useModal } from '/@/components/Modal';

  const emit = defineEmits(['success', 'register', 'successPrint']);

  const { t } = useI18n('order.flow.wx.m8OrderFlowWxOut');
  const { showMessage } = useMessage();
  const record = ref<M8OrderFlowWxOut>({} as M8OrderFlowWxOut);
  const itemCodes = ref('');
  const itemNames = ref('');
  const queryParams = ref({
    'oper.operCode': 'WX',
  });
  const selectType = ref('flowSelect');
  let loading = ref(false);
  const tableRef = ref();

  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增数铣送检') : t('编辑数铣送检'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('报检人'),
      field: 'user.userName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('报检时间'),
      field: 'repDate',
      component: 'Input',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      // required: true,
      dynamicDisabled: true,
    },
    {
      label: t('送检明细'),
      field: 'checkList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'm8OrderFlowWxOutRdsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerM8OrderFlowWxOutRdsTable, m8OrderFlowWxOutRdsTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record1: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleM8OrderFlowWxOutRdsDelete.bind(this, record1),
          },
          auth: 'm8:machine:caozuo',
          // ifShow: record.value.allowEdit,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    indexColumnProps: {
      width: 20,
    }
  });

  async function setM8OrderFlowWxOutRdsTableData(_res: Recordable) {
  // 定义错误信息列

    const normalColumns = [
      {
        title: t('图纸'),
        dataIndex: 'orderPic.picname',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        slot: 'firstColumn',
        // ifShow: (record) => !record.erroMsg,
      },
      {
        title: t('工序'),
        dataIndex: 'operCode',
        width: 70,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        ifShow: (record) => !record.erroMsg,
      },
      {
        title: t('工序名称'),
        dataIndex: 'oper.operName',
        width: 70,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        ifShow: (record) => !record.erroMsg,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 70,
        align: 'center',
        // editRow: true,
        editRow: (record) => !!record.erroMsg,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: (record) => !!record.erroMsg,
        ifShow: (record) => !record.erroMsg,
      },
    ];

    const allColumns = [...normalColumns];
    console.log('allColumns', allColumns);
    m8OrderFlowWxOutRdsTable.setColumns(allColumns);
    m8OrderFlowWxOutRdsTable.setTableData(record.value.checkList || []);
    // 使用 nextTick 确保表格渲染完成后执行编辑操作
    nextTick(() => {
      const dataSource = m8OrderFlowWxOutRdsTable.getDataSource();
      dataSource.forEach((record, index) => {
        if (!record.erroMsg) {
          // 触发 onEdit 方法开启编辑
          record.onEdit?.(true, false);
        }
      });
    });
  }

  function handleM8OrderFlowWxOutRdsRowClick(record: Recordable) {
    if (record.erroMsg) {
      return;
    }
    record.onEdit?.(true, false);
  }

  function handleM8OrderFlowWxOutRdsAdd() {
    document.getElementById('form_item_selIds')?.click();
  }

  function handleM8OrderFlowWxOutRdsDelete(record: Recordable) {
    m8OrderFlowWxOutRdsTable.deleteTableDataRecord(record);
  }

  async function getM8OrderFlowWxOutRdsList() {

    let m8OrderFlowWxOutRdsList: Recordable[] = [];
    for (const record of m8OrderFlowWxOutRdsTable.getDataSource()) {
      if (!record.erroMsg) {
        m8OrderFlowWxOutRdsList.push({
          ...record,
          iqty: record?.editValueRefs?.iqty || record.iqty,
        });
      } 
    }
    return m8OrderFlowWxOutRdsList;
  }
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    loading.value = true;
    setDrawerProps({ loading: true });
    await resetFields();
    // const res = await m8OrderFlowWxOutForm(data);
    record.value = (data || {}) as M8OrderFlowWxOut;
    setDrawerProps({ showOkBtn: record.value.allowEdit});
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setM8OrderFlowWxOutRdsTableData(record.value.checkList);
    // record.value = (res.m8OrderFlowWxOut || {}) as M8OrderFlowWxOut;
    // setDrawerProps({ showOkBtn: record.value.allowEdit });
    loading.value = false;
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      loading.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
      };
      data.checkList = await getM8OrderFlowWxOutRdsList();
      const res = await repCheck(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', res.data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
      tableRef.value.setProps({ editable: true });
    } finally {
      loading.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }
</style>
